package com.jdk.demo.forkJoinPool;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinPoolTest {

	public static void main(String[] args) {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        JymForkJoinDemo jymForkJoinDemo = new JymForkJoinDemo(0L,100L);
        System.out.println(forkJoinPool.invoke(jymForkJoinDemo));
        long end = System.currentTimeMillis();
        System.out.println(end-start);
        long sum = 0L;
        for (long i =0L; i<100L;i++){
            sum +=i;
        }
        long end1 = System.currentTimeMillis();
        System.out.println(sum);
        System.out.println(end1-end);
    }
	
}

class JymForkJoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    public JymForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    public static final Long BORDER = 50L;

    protected Long compute() {
        long length = end - start;
        if (length<=BORDER){
            long sum = 0L;
            for(long i= start; i<end;i++){
                sum +=i;
            }
            return sum;
        }else {
        	// 线程在执行当前ForkJoinTask的时候，产生了left、right 两个子Task。所谓fork，是指把这两个子Task放入队列里面，join（）则是要等待2个子Task完成。而子Task在执行过程中，会再次产生两个子Task。如此层层嵌套，类似于递归调用，直到最底层的Task计算完成，再一级级返回
            long middle = (start+end)/2;
            JymForkJoinDemo left = new JymForkJoinDemo(start,middle);
            left.fork();
            JymForkJoinDemo right = new JymForkJoinDemo(middle,end);
            right.fork();
            return left.join()+right.join();
        }
    }
}